package com.pap.gateway.config.security.handler;

import com.alibaba.fastjson.JSON;
import com.pap.obj.vo.response.ResponseVO;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 自定义的 AccessDenied， 统一错误码， 改为 JSON，同时 http.status.code 改为 200， 方便理解
 */
public class RestAuthenticationAccessDeniedHandler implements ServerAccessDeniedHandler {

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, AccessDeniedException e) {
        return Mono.defer(() -> Mono.just(exchange.getResponse()))
                .flatMap(response -> {
                    response.setStatusCode(HttpStatus.OK);
                    response.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
                    DataBufferFactory dataBufferFactory = response.bufferFactory();
                    DataBuffer buffer = dataBufferFactory.wrap(JSON.toJSONBytes(ResponseVO.forbidden("PAP ACCESS DENIED")));
                    return response.writeWith(Mono.just(buffer))
                            .doOnError( error -> DataBufferUtils.release(buffer));
                });
    }
}